<?php

namespace backend\models\service;

use Yii;
use yii\data\Sort;
use yii\data\ActiveDataProvider;
use backend\models\odm\UserConsumeOdm;

class Order extends UserConsumeOdm {

    private $_query;
    public $novel_title;
    public $phone;
    public $main;
    public $category;

    public function init() {
        parent::init();
        $this->_query = static::find();
    }
    
    public function getNovel()
    {
        return $this->hasMany(\backend\models\service\NovelService::className(), ['novel_id' => 'novel_id']);
    }
    
    public function getUser()
    {
        return $this->hasMany(\backend\models\User::className(), ['user_id' => 'user_id']);
    }
    
    /**
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function getQuerySearch($params) {
        $this->load($params);
        $this->_query->joinWith('novel as n')->joinWith('user as u');
        $this->_query->andFilterWhere([
            'id' => $this->id,
            'n.novel_main_category' => $this->main,
            'n.novel_category' => $this->category,
            'status' => $this->status,
        ]);
        $this->_query->andFilterWhere(['like','u.user_phone',$this->phone]);
        if(isset($this->novel_title)){
            $this->_query->andFilterWhere(['like','n.novel_title',$this->novel_title]);
        }
        $this->time($this->_query, [
            'pay_time',
        ]);
        return $this;
    }

    public function getList() {
        $query = $this
            ->getQuerySearch(Yii::$app->request->queryParams)
            ->getQuery();

        return new ActiveDataProvider([
            'query' => $query,
        ]);
    }

    /**
     *
     * 时间的搜索
     *
     * @param $query , array $colmns
     *
     * @return $query
     * */
    private function time(&$query, $colmns) {
        foreach ($colmns as $key => $value) {
            if ($this->$value != '') {
                $query->andWhere(['between', $value, strtotime($this->$value), strtotime($this->$value) + 86400]);
            } else {
                $this->$value = null;
            }
        }
        return $query;
    }

    public function getQuery() {
        return $this->_query;
    }
}
